// vite.config.js
import { defineConfig } from 'vite'
import fs from 'fs'
import path from 'path'

interface VueFileInfo {
  importPath: string
  coverPath: string
  component: string
  importComponent: string
}
export  function componentListPlugin() {
  let base = ''
  return {
    name: 'vite-plugin-component-list',
    configResolved(resolvedConfig) {
      // resolvedConfig.base 就是最终的 base 路径
      const _base= resolvedConfig.base.split('/').filter(Boolean).join('/')
      console.log(_base)
      if(_base){
        base = `/${_base}/`
      }

    },
    configureServer(server) {
      server.middlewares.use(async (req, res, next) => {
        if (req.url === '/component') {

          const dir = path.resolve(process.cwd(), `src/components`)
          const getVueFileList = (root: string): VueFileInfo[] => {
            const result: VueFileInfo[] = []

            const walk = (dir: string) => {
              const files = fs.readdirSync(dir, { withFileTypes: true })
              for (const f of files) {
                const fullPath = path.join(dir, f.name)
                if (f.isDirectory()) {
                  walk(fullPath) // 递归子目录
                } else if (f.isFile() && f.name.endsWith(".vue")) {
                  const basename = path.basename(f.name, ".vue")
                  const exts = [".svg", ".png", ".jpg", ".jpeg"]

                  // 在同目录下查找同名的图片文件
                  const coverFile = exts
                    .map(ext => path.join(dir, basename + ext))
                    .find(p => fs.existsSync(p))

                  if (coverFile) {
                    const relativeComponent = path.relative(root, fullPath).replace(/\\/g, "/")
                    const relativeCover = path.relative(root, coverFile).replace(/\\/g, "/")
                    const cover = `@/components/${relativeCover}`
                    const coverPath = relativeCover.replace(/[\.\\\/]/g, "_")
                    const nameWithoutExt = path.basename(relativeCover, path.extname(relativeCover))
                    console.log(nameWithoutExt) // 例如: "IconTooling"
                    const importPath = `import ${coverPath} from '${cover}'`
                    const component = `@/components/${relativeComponent}`
                    result.push({
                      importPath,
                      coverPath,
                      component,
                      importComponent:`import ${nameWithoutExt} from \'${component}\'`
                    })
                  }
                }
              }
            }

            walk(root)
            return result
          }
          const files = getVueFileList(dir)
          const fileContent =
`${files.map(file => {
  return file.importPath
}).join('\n')}

export default [
${files.map(file => {
  return `  {
    coverPath: ${file.coverPath},
    component: '${file.component}',
    importComponent: ${JSON.stringify(file.importComponent)},
  },`
}).join('\n')}
]
`
          fs.writeFileSync(path.resolve(process.cwd(), 'src/components/server/componentData.ts'),fileContent)

          const listHtml = `
<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="UTF-8">
    <link rel="icon" href="/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>大屏组件预览</title>
    <style>
    :root {
      color-scheme: dark; /* 告诉浏览器这是深色模式 */
      background-color: #121212;
      color: #eee;
    }
    </style>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="${base}/src/components/server/main.ts"></script>
  </body>
</html>
          `
          res.setHeader('Content-Type', 'text/html; charset=utf-8')
          res.end(listHtml)
          return
        }
        next()
      })
    },
  }
}

